<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能推荐助手 - 外卖平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.15);
            max-width: 800px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            color: #333;
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .header p {
            color: #666;
            font-size: 1.1rem;
        }
        
        .ai-chat {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            min-height: 300px;
            max-height: 400px;
            overflow-y: auto;
        }
        
        .chat-message {
            margin-bottom: 15px;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }
        
        .chat-message.user {
            flex-direction: row-reverse;
        }
        
        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            flex-shrink: 0;
        }
        
        .ai-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .user-avatar {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
        }
        
        .message-content {
            background: white;
            padding: 15px;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 70%;
            word-wrap: break-word;
        }
        
        .chat-message.user .message-content {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
        }
        
        .message-time {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
        
        .input-area {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .input-field {
            flex: 1;
            padding: 15px;
            border: 2px solid #e9ecef;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: all 0.3s ease;
        }
        
        .input-field:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .send-btn {
            padding: 15px 25px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .send-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }
        
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .quick-btn {
            padding: 10px 15px;
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 20px;
            cursor: pointer;
            text-align: center;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .quick-btn:hover {
            border-color: #667eea;
            background: #f8f9fa;
        }
        
        .recommendations {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .recommendation-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px;
            border: 1px solid #e9ecef;
            border-radius: 10px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }
        
        .recommendation-item:hover {
            border-color: #667eea;
            box-shadow: 0 2px 10px rgba(102, 126, 234, 0.1);
        }
        
        .dish-image {
            width: 60px;
            height: 60px;
            border-radius: 10px;
            object-fit: cover;
        }
        
        .dish-info {
            flex: 1;
        }
        
        .dish-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .dish-price {
            color: #ff6b6b;
            font-weight: 600;
            font-size: 18px;
        }
        
        .dish-reason {
            color: #666;
            font-size: 12px;
            margin-top: 5px;
        }
        
        .add-btn {
            padding: 8px 16px;
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
        }
        
        .back-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(255, 107, 107, 0.8);
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            cursor: pointer;
            color: white;
            font-size: 20px;
            transition: all 0.3s ease;
            z-index: 1000;
        }
        
        .back-btn:hover {
            background: #ff6b6b;
            transform: scale(1.1);
        }
        
        .typing-indicator {
            display: none;
            align-items: center;
            gap: 10px;
            color: #666;
            font-style: italic;
        }
        
        .typing-dots {
            display: flex;
            gap: 3px;
        }
        
        .typing-dot {
            width: 6px;
            height: 6px;
            background: #667eea;
            border-radius: 50%;
            animation: typing 1.4s infinite;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes typing {
            0%, 60%, 100% {
                transform: translateY(0);
            }
            30% {
                transform: translateY(-10px);
            }
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 20px;
                margin: 10px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .quick-actions {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <button class="back-btn" onclick="goBack()">←</button>
    
    <div class="container">
        <div class="header">
            <h1>🤖 AI智能推荐助手</h1>
            <p>与AI助手对话，获得个性化美食推荐</p>
        </div>
        
        <div class="ai-chat" id="chatContainer">
            <div class="chat-message">
                <div class="message-avatar ai-avatar">🤖</div>
                <div class="message-content">
                    <div>👋 您好！我是小智，您的专属美食推荐助手</div>
                    <div class="message-time">刚刚</div>
                </div>
            </div>
            <div class="chat-message">
                <div class="message-avatar ai-avatar">🤖</div>
                <div class="message-content">
                    <div>🍽️ 我可以根据您的时间、天气、口味偏好为您推荐最适合的美食</div>
                    <div class="message-time">刚刚</div>
                </div>
            </div>
            <div class="chat-message">
                <div class="message-avatar ai-avatar">🤖</div>
                <div class="message-content">
                    <div>💡 您可以直接问我，比如"我想吃辣的"、"推荐点清淡的"、"今天适合吃什么"</div>
                    <div class="message-time">刚刚</div>
                </div>
            </div>
        </div>
        
        <div class="quick-actions">
            <div class="quick-btn" onclick="sendQuickMessage('我想吃辣的')">🌶️ 我想吃辣的</div>
            <div class="quick-btn" onclick="sendQuickMessage('推荐点清淡的')">🥗 推荐点清淡的</div>
            <div class="quick-btn" onclick="sendQuickMessage('今天适合吃什么')">🍽️ 今天适合吃什么</div>
            <div class="quick-btn" onclick="sendQuickMessage('推荐点健康的')">🥕 推荐点健康的</div>
            <div class="quick-btn" onclick="sendQuickMessage('我想吃甜的')">🍰 我想吃甜的</div>
            <div class="quick-btn" onclick="sendQuickMessage('推荐点实惠的')">💰 推荐点实惠的</div>
        </div>
        
        <div class="input-area">
            <input type="text" class="input-field" id="messageInput" placeholder="输入您想说的话..." onkeypress="handleKeyPress(event)">
            <button class="send-btn" onclick="sendMessage()">发送</button>
        </div>
        
        <div class="typing-indicator" id="typingIndicator">
            <div class="message-avatar ai-avatar">🤖</div>
            <div>AI正在思考</div>
            <div class="typing-dots">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            </div>
        </div>
        
        <div class="recommendations" id="recommendations" style="display: none;">
            <h3>🍽️ 为您推荐</h3>
            <div id="recommendationsList"></div>
        </div>
    </div>
    
    <script src="../database.js"></script>
    <script src="enhanced-ai-engine.js"></script>
    <script>
        let currentUser = null;
        let chatHistory = [];
        
        // 页面加载时初始化
        window.onload = function() {
            // 检查登录状态
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
            } else {
                // 如果没有登录，重定向到登录页面
                window.location.href = '../pages/login.html';
                return;
            }
            
            // 初始化AI助手
            initializeAI();
        };
        
        function initializeAI() {
            // 发送欢迎消息
            setTimeout(() => {
                addAIMessage("根据当前时间和天气，我为您推荐一些美食。您也可以直接告诉我您的需求！");
            }, 1000);
        }
        
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }
        
        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (message === '') return;
            
            // 添加用户消息
            addUserMessage(message);
            
            // 清空输入框
            input.value = '';
            
            // 处理AI响应
            processUserMessage(message);
        }
        
        function sendQuickMessage(message) {
            document.getElementById('messageInput').value = message;
            sendMessage();
        }
        
        function addUserMessage(message) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'chat-message user';
            messageDiv.innerHTML = `
                <div class="message-avatar user-avatar">👤</div>
                <div class="message-content">
                    <div>${message}</div>
                    <div class="message-time">${new Date().toLocaleTimeString()}</div>
                </div>
            `;
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        function addAIMessage(message) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'chat-message';
            messageDiv.innerHTML = `
                <div class="message-avatar ai-avatar">🤖</div>
                <div class="message-content">
                    <div>${message}</div>
                    <div class="message-time">${new Date().toLocaleTimeString()}</div>
                </div>
            `;
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        function showTypingIndicator() {
            document.getElementById('typingIndicator').style.display = 'flex';
        }
        
        function hideTypingIndicator() {
            document.getElementById('typingIndicator').style.display = 'none';
        }
        
        async function processUserMessage(message) {
            showTypingIndicator();
            
            try {
                // 分析用户意图
                const intent = analyzeUserIntent(message);
                
                // 根据意图生成响应
                let response = '';
                let recommendations = [];
                
                switch (intent.type) {
                    case 'spicy':
                        response = "🌶️ 您喜欢辣味！我为您推荐一些香辣美食：";
                        recommendations = await getSpicyRecommendations();
                        break;
                        
                    case 'light':
                        response = "🥗 清淡口味！我为您推荐一些清爽美食：";
                        recommendations = await getLightRecommendations();
                        break;
                        
                    case 'healthy':
                        response = "🥕 健康饮食！我为您推荐一些营养美食：";
                        recommendations = await getHealthyRecommendations();
                        break;
                        
                    case 'sweet':
                        response = "🍰 甜食爱好者！我为您推荐一些香甜美食：";
                        recommendations = await getSweetRecommendations();
                        break;
                        
                    case 'budget':
                        response = "💰 经济实惠！我为您推荐一些性价比高的美食：";
                        recommendations = await getBudgetRecommendations();
                        break;
                        
                    case 'general':
                        response = "🍽️ 根据当前时间和天气，我为您推荐一些美食：";
                        recommendations = await getGeneralRecommendations();
                        break;
                        
                    default:
                        response = "🤔 我理解您的需求，让我为您推荐一些美食：";
                        recommendations = await getGeneralRecommendations();
                }
                
                // 强力兜底：若仍无结果，返回热门菜或任意菜
                if (!recommendations || recommendations.length === 0) {
                    const any = getAnyDishes(5);
                    if (any.length > 0) {
                        recommendations = any;
                        response = "📌 当前条件下暂无完全匹配，我为您推荐一些人气菜品：";
                    }
                }

                // 延迟响应，模拟AI思考
                setTimeout(() => {
                    hideTypingIndicator();
                    addAIMessage(response);
                    
                    if (recommendations.length > 0) {
                        showRecommendations(recommendations);
                    } else {
                        addAIMessage("抱歉，暂时没有找到合适的推荐，请尝试其他需求。");
                    }
                }, 1500 + Math.random() * 1000);
                
            } catch (error) {
                hideTypingIndicator();
                addAIMessage("抱歉，我遇到了一些问题，请稍后再试。");
                console.error('AI处理失败:', error);
            }
        }
        
        function analyzeUserIntent(message) {
            const lowerMessage = message.toLowerCase();
            
            if (lowerMessage.includes('辣') || lowerMessage.includes('香辣') || lowerMessage.includes('麻辣')) {
                return { type: 'spicy', confidence: 0.9 };
            }
            
            if (lowerMessage.includes('清淡') || lowerMessage.includes('清爽') || lowerMessage.includes('不辣')) {
                return { type: 'light', confidence: 0.9 };
            }
            
            if (lowerMessage.includes('健康') || lowerMessage.includes('营养') || lowerMessage.includes('养生')) {
                return { type: 'healthy', confidence: 0.9 };
            }
            
            if (lowerMessage.includes('甜') || lowerMessage.includes('甜品') || lowerMessage.includes('蛋糕')) {
                return { type: 'sweet', confidence: 0.9 };
            }
            
            if (lowerMessage.includes('实惠') || lowerMessage.includes('便宜') || lowerMessage.includes('经济')) {
                return { type: 'budget', confidence: 0.9 };
            }
            
            if (lowerMessage.includes('推荐') || lowerMessage.includes('吃什么') || lowerMessage.includes('适合')) {
                return { type: 'general', confidence: 0.8 };
            }
            
            return { type: 'general', confidence: 0.5 };
        }
        
        async function getSpicyRecommendations() {
            // 优先用AI引擎推荐后再按需求过滤
            if (window.enhancedAIRecommendationEngine && currentUser) {
                const result = await enhancedAIRecommendationEngine.generateRecommendations(currentUser.id, 20);
                let list = (result.recommendations || []).filter(d =>
                    includesAny(d.name, ['辣','麻']) || includesAny(d.description, ['辣','麻']) || includesAny(d.category, ['川','香辣'])
                );
                if (list.length >= 5) return list.slice(0, 5);
            }
            const db = new Database();
            const dishes = db.getDishes();
            let list = dishes.filter(dish => 
                includesAny(dish.name, ['辣','麻']) || includesAny(dish.description, ['辣','麻']) || includesAny(dish.category, ['川','香辣'])
            );
            if (list.length < 5) list = fallbackPopular(dishes, list);
            return list.slice(0, 5);
        }
        
        async function getLightRecommendations() {
            if (window.enhancedAIRecommendationEngine && currentUser) {
                const result = await enhancedAIRecommendationEngine.generateRecommendations(currentUser.id, 20);
                let list = (result.recommendations || []).filter(d =>
                    includesAny(d.name, ['清淡','清爽','凉']) || includesAny(d.description, ['清淡','清爽','凉']) || includesAny(d.category, ['汤','粥','沙拉','素'])
                );
                if (list.length >= 5) return list.slice(0, 5);
            }
            const db = new Database();
            const dishes = db.getDishes();
            let list = dishes.filter(d => 
                includesAny(d.name, ['清淡','清爽','凉']) || includesAny(d.description, ['清淡','清爽','凉']) || includesAny(d.category, ['汤','粥','沙拉','素'])
            );
            if (list.length < 5) list = fallbackPopular(dishes, list);
            return list.slice(0, 5);
        }
        
        async function getHealthyRecommendations() {
            if (window.enhancedAIRecommendationEngine && currentUser) {
                const result = await enhancedAIRecommendationEngine.generateRecommendations(currentUser.id, 20);
                let list = (result.recommendations || []).filter(d =>
                    includesAny(d.name, ['健康','营养','素']) || includesAny(d.description, ['健康','营养','低脂','少油']) || includesAny(d.category, ['沙拉','素食'])
                );
                if (list.length >= 5) return list.slice(0, 5);
            }
            const db = new Database();
            const dishes = db.getDishes();
            let list = dishes.filter(d => 
                includesAny(d.name, ['健康','营养','素']) || includesAny(d.description, ['健康','营养','低脂','少油']) || includesAny(d.category, ['沙拉','素食'])
            );
            if (list.length < 5) list = fallbackPopular(dishes, list);
            return list.slice(0, 5);
        }
        
        async function getSweetRecommendations() {
            if (window.enhancedAIRecommendationEngine && currentUser) {
                const result = await enhancedAIRecommendationEngine.generateRecommendations(currentUser.id, 20);
                let list = (result.recommendations || []).filter(d =>
                    includesAny(d.name, ['甜','奶','蜜']) || includesAny(d.description, ['甜','奶','蜜']) || includesAny(d.category, ['甜品','蛋糕','饮品','水果'])
                );
                if (list.length >= 5) return list.slice(0, 5);
            }
            const db = new Database();
            const dishes = db.getDishes();
            let list = dishes.filter(d => 
                includesAny(d.name, ['甜','奶','蜜']) || includesAny(d.description, ['甜','奶','蜜']) || includesAny(d.category, ['甜品','蛋糕','饮品','水果'])
            );
            if (list.length < 5) list = fallbackPopular(dishes, list);
            return list.slice(0, 5);
        }
        
        async function getBudgetRecommendations() {
            if (window.enhancedAIRecommendationEngine && currentUser) {
                const result = await enhancedAIRecommendationEngine.generateRecommendations(currentUser.id, 20);
                let list = (result.recommendations || []).filter(d => d.price < 30);
                if (list.length >= 5) return list.slice(0, 5);
            }
            const db = new Database();
            const dishes = db.getDishes();
            let list = dishes.filter(d => d.price < 30);
            if (list.length < 5) list = fallbackPopular(dishes, list);
            return list.slice(0, 5);
        }
        
        async function getGeneralRecommendations() {
            try {
                if (window.enhancedAIRecommendationEngine && currentUser) {
                    const result = await enhancedAIRecommendationEngine.generateRecommendations(currentUser.id, 10);
                    if (result && result.recommendations && result.recommendations.length > 0) {
                        return result.recommendations;
                    }
                }
                // 兜底：直接返回评分/销量靠前的菜
                return getAnyDishes(5);
            } catch (e) {
                return getAnyDishes(5);
            }
        }
        
        function showRecommendations(recommendations) {
            const recommendationsDiv = document.getElementById('recommendations');
            const recommendationsList = document.getElementById('recommendationsList');
            const db = new Database();
            
            if (recommendations.length === 0) {
                addAIMessage("抱歉，暂时没有找到合适的推荐。");
                return;
            }
            
            recommendationsList.innerHTML = recommendations.map(dish => {
                const merchant = dish.merchantId ? db.getMerchantById(dish.merchantId) : null;
                const merchantName = merchant ? merchant.name : '';
                return `
                <div class="recommendation-item">
                    <img src="${dish.image}" alt="${dish.name}" class="dish-image" onerror="this.src='https://via.placeholder.com/60x60?text=菜品'">
                    <div class="dish-info">
                        <div class="dish-name">${dish.name}</div>
                        <div class="dish-price">¥${dish.price}</div>
                        <div class="dish-reason">${merchantName ? '商家：' + merchantName + ' · ' : ''}${dish.recommendationReason || '为您精心推荐'}</div>
                    </div>
                    <button class="add-btn" onclick="addToCart(${dish.id})">加入购物车</button>
                </div>
            `}).join('');
            
            recommendationsDiv.style.display = 'block';
        }

        // 小工具：包含任一关键字
        function includesAny(text, keywords) {
            if (!text) return false;
            const t = String(text).toLowerCase();
            return keywords.some(k => t.indexOf(String(k).toLowerCase()) !== -1);
        }

        // 填充推荐不足时的热门备选（按评分和销量排序）
        function fallbackPopular(all, current) {
            const set = new Set(current.map(d => d.id));
            const rest = all.filter(d => !set.has(d.id));
            rest.sort((a,b) => (b.rating || 0) - (a.rating || 0) || (b.sales || 0) - (a.sales || 0));
            return current.concat(rest).slice(0, Math.max(5, current.length));
        }

        // 任意取菜（用于兜底）
        function getAnyDishes(n) {
            try {
                const db = new Database();
                const dishes = db.getDishes();
                if (!dishes || dishes.length === 0) return [];
                return dishes.sort((a,b) => (b.rating || 0) - (a.rating || 0) || (b.sales || 0) - (a.sales || 0)).slice(0, n);
            } catch (e) {
                return [];
            }
        }
        
        function addToCart(dishId) {
            const dish = new Database().getDishById(dishId);
            if (!dish) return;
            
            // 记录用户行为
            if (window.enhancedAIRecommendationEngine) {
                enhancedAIRecommendationEngine.learnFromUserBehavior(currentUser.id, 'click', {
                    dishId: dishId,
                    context: {
                        time: new Date().toISOString(),
                        source: 'ai-chat'
                    }
                });
            }
            
            // 添加到购物车
            let cart = JSON.parse(localStorage.getItem('cart') || '[]');
            const existingItem = cart.find(item => item.id === dishId);
            
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push({
                    id: dish.id,
                    name: dish.name,
                    price: dish.price,
                    image: dish.image,
                    quantity: 1,
                    merchantId: dish.merchantId
                });
            }
            
            localStorage.setItem('cart', JSON.stringify(cart));
            
            // 显示成功消息
            addAIMessage(`✅ 已将"${dish.name}"加入购物车！`);
        }
        
        function goBack() {
            window.location.href = '../pages/user.html';
        }
    </script>
</body>
</html>
